from server.model import User, Department, FormattedText
from transfer.service import BaseService, RegisterFunction
from .msgsvr import Service

send_status = (
    (1, '已发送'),
    (2, '已接收'),
    (3, '已回执'),
)
receive_status = (
    (0, '未接收'),
    (1, '新接收'),
    (2, '已查看'),
    (3, '已回复'),
)


class Services(Service):
    """
    服务类，该类的所有共有函数将都被自动注册到RPC服务器中
    """

    def login(self, name, pwd):
        user = User()
        return user.check_pwd(name, pwd)

    #############################################
    # 服务端示例代码
    def get_all_user_name(self, role=None):
        """
        调用实体类完成：获取所有用户的功能（或业务）
        """
        user = User()
        if role:
            return user.get(['number'], [['role', role]]).as_dict()
        else:
            return user.get(['number']).as_dict()

    def user_get_all(self):
        """
        调用实体类完成：获取所有用户 的功能（或业务）
        """
        user = User()
        return user.get_all()

    def add_user(self, kwargs: dict):
        """
        kwargs = {'列名1': 值, '列名2': 值, ...}
        """
        user = User()
        user.add_one(**kwargs)

    def del_user(self, uid: str):
        user = User()
        user.delete([['number', uid]])

    def update_user(self, uname, kwargs: dict):
        u = User()
        u.set([['number', uname]], **kwargs)

    def department_get_all(self):
        dep = Department()
        return dep.get(['id', 'name', 'parent']).as_list()

    def send_msg(self, msg: dict):
        if msg:
            time = FormattedText.get_current_time()
            for r in msg.get('receiver', []):
                fm = FormattedText()
                msg.update({
                    'datetime': time,
                    'receiver': r,
                    'sstatus': '已发送',
                    'rstatus': '未接收'
                })
                print('发送消息：', msg)
                fm.add_one(**msg)

    def get_inbox(self, number):
        FormattedText().set({'receiver': number,
                             'receiverdel': 0,
                             'rstatus': '未接收'},
                            rstatus='新接收',
                            sstatus='已接收')
        t = FormattedText().get(
            ('id', 'datetime', 'sender', 'rstatus', 'text', 'receipt', 'fmsg'),
            {'receiver': number, 'receiverdel': 0}, order_by=[['datetime', 'DESC']])
        return t.as_dict() if t else ()

    def get_outbox(self, number):
        t = FormattedText().get(
            ('id', 'datetime', 'receiver', 'sstatus', 'text', 'receipt', 'fmsg'),
            {'sender': number, 'senderdel': 0},  order_by=[['datetime', 'DESC']])
        return t.as_dict() if t else ()

    def inbox_read(self, number, text_id):
        FormattedText().set(
            {'receiver': number, 'id': int(text_id), 'rstatus': '新接收'},
            rstatus='已阅读', sstatus='已阅读')

    def inbox_receipt(self, number, text_id, receipt):
        FormattedText().set({'receiver': number, 
                            'id': int(text_id), 
                            'rstatus': '已阅读'},
                            rstatus='已回执', sstatus='已回执', 
                            receipt=receipt)

    def inbox_text_del(self, number, text_id):
        FormattedText().set({'id': int(text_id), 'receiver': number},
                            receiverdel=1)

    def outbox_text_del(self, number, text_id):
        FormattedText().set({'id': int(text_id), 'sender': number},
                            senderdel=1)
